package com.titaniume.lock;


import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ProjectName: juc
 * @Package: com.titaniume.lock
 * @ClassName: ThreadDemo4
 * @Author: huangrenfei
 * @Description: 集合不安全演示
 * @Date: 2021/11/22 15:41
 * @Version: 1.0
 */
public class ThreadDemo4 {


    public static void main(String[] args) {

//        testArrayList();
//        testHashSet();
        testHashMap();
    }





    //ArrayList集合线程不安全演
    public static void testArrayList() {
        //创建ArrayList 集合
//        ArrayList<String> list = new ArrayList<>();


        //方式一：Vector解决线程安全
//        Vector<String> list = new Vector<>();

        //方式二： Collections
//        List<String> list = Collections.synchronizedList(new ArrayList<>());


        //方式三：CopyOnWriteArrayList （推荐使用）
        //写时复制技术
        //并发读 单独写 每次写先复制一份 然后再合并 就不会发生并发修改异常
        CopyOnWriteArrayList list = new CopyOnWriteArrayList<String>();


        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                //添加数据 add() 方法 没有synchronized 线程不安全
                list.add(UUID.randomUUID().toString().substring(0, 8));
                //获取数据
                //出现并发修改异常 Exception in thread "8" java.util.ConcurrentModificationException
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
    }


    //HashSet 线程不安全演示
    public static void testHashSet() {

//        HashSet<String> hashSet = new HashSet<>();

        CopyOnWriteArraySet<String> hashSet = new  CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                //添加数据
                hashSet.add(UUID.randomUUID().toString().substring(0, 8));
                //获取数据
                System.out.println(hashSet);
            }, String.valueOf(i)).start();
        }
    }


    //HashMap 线程不安全演示
    public static void testHashMap() {
//        HashMap<String,String> hashMap = new HashMap<>();

        ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>();

        for (int i = 0; i < 30; i++) {
            String key = String.valueOf(i);
            new Thread(() -> {
                //添加数据
                hashMap.put(key,UUID.randomUUID().toString().substring(0, 8));
                //获取数据
                System.out.println(hashMap);
            }, String.valueOf(i)).start();
        }
    }
}
